<?php
class Gradelevel{
	public $money;
	public $order;
	public $site_id;
	public $userlist;
	public $orderdb;
	public $memberdb;
	public $member_id;
	public $error = array();
	//构造函数
	public function Gradelevel($order_id = 0, $site_id = 0, $member_id = 0){
		$this->memberdb = D('Member');
		$this->orderdb = D('Order');
		$this->saledb = M('Sale');
		$this->money = $this->getmoney();
		$this->site_id = $site_id;
		
		$db = M('Affiliatesetting');
		$affsetting = $db -> where(array('site_id' => $this->site_id,'classname' => 'Gradelevel')) -> find();
		$this -> affsettingarr = unserialize($affsetting['value']);
		
		$this->order = $this->orderdb -> where(array('id' => $order_id)) -> find();
		
		$this->member_id = $member_id > 0? $member_id: $this->order['member_id'];
		if(!$this->order){
			$this->error['info'] = '订单不存在！';
		}
		
		$this->updateUserLevel();
	}
	public function sendMsg(){}
	//创建设置项表单
	public function createform(){
		
		$db = M('Affiliatesetting');
		
		$ret = array ('level' => array ( 0,0,0),'levelnamebase' => 'VIP会员', 'changelevel' => '恭喜您升级成为：@levelname@');
		
		
		
		$ret = $db -> where(array('site_id' => $this->site_id,'classname' => 'Gradelevel')) -> find();
		$ret = unserialize($ret['value']);
		//F('ret',$ret);
		$html = '


<table cellpadding="0" class="Gradelevel" cellspacing="0" border="1" width="100%">
<tr>
    <td align="center" valign="middle" style="width:150px;">分销资格等级名称</td>
    <td align="left" colspan="2"><input type="text" name="levelnamebase" value="'.$ret['levelnamebase'].'" /></td>
  </tr>
  
  
  <tr>
    <td align="center" valign="middle" style="width:150px;">会员升级后通知信息</td>
    <td align="left" colspan="2"><input style="width:100%" type="text" name="changelevel" value="'.$ret['changelevel'].'" /><br>
等级名称@levelname@
</td>
  </tr>
  
  
  <tr>
    <td align="center" valign="middle" style="width:150px;">分销资格最低消费</td>
    <td align="left" colspan="2"><input type="text" name="levelmoney" value="'.$ret['levelmoney'].'" /></td>
  </tr>
  
  
</table>
<br>

<style>.Gradelevel td{padding:5px;}</style><table class="Gradelevel" border="1" cellspacing="0" cellpadding="5" width="100%">
  <tr>
    <th align="center" style="text-align:center; width:100px;">级别</th>
    <th align="center" style="text-align:center;">分成比例</th>
  </tr>
  
  <tr>
    <td align="center" valign="middle">1</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][0].'" />%</td>
  </tr>
  <tr>
    <td align="center" valign="middle">2</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][1].'" />%</td>
  </tr>
  <tr>
    <td align="center" valign="middle">3</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][2].'" />%</td>
  </tr>
  <tr>
    <td align="center" valign="middle">4</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][3].'" />%</td>
  </tr>
  <tr>
    <td align="center" valign="middle">5</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][4].'" />%</td>
  </tr>
  <tr>
    <td align="center" valign="middle">6</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][5].'" />%</td>
  </tr>
  <tr>
    <td align="center" valign="middle">7</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][6].'" />%</td>
  </tr>
  <tr>
    <td align="center" valign="middle">8</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][7].'" />%</td>
  </tr>
  
</table>
';

        return $html;
	}
	
	//保存设置项
	public function saveform(){
		if(isset($_POST['level'])){
			$data['classname'] = 'Gradelevel';
			$data['value'] = serialize($_POST);
			$data['site_id'] = $this->site_id;
			$db = M('Affiliatesetting');
			$pc = (float)$_POST['rlevel'][0];
			foreach($_POST['level'] as $v){
				$pc += (float)$v;
			}
			if($pc > 100){
				$this->error['info'] = '设置错误，分成比的和大于100！';
				return false;
			}
			//dump($data);
			$ret = $db -> where(array('site_id' => $data['site_id'],'classname' => $data['classname'])) -> find();
			if($ret){
				$saveret = $db -> where(array('site_id' => $data['site_id'],'classname' => $data['classname'])) -> data(array('value' => $data['value'])) -> save();
			}else{
				$saveret = $db -> data($data) -> add();
			}
			if($saveret){
				return true; 
			}else{
				$this->error['info'] = $db -> getLastSql();
				return false;
			}
			
		}
	}
	
	
	public function updateUserLevel(){
		$db = M('Affiliatesetting');
		$affsetting = $db -> where(array('site_id' => $this->site_id,'classname' => 'Gradelevel')) -> find();
		$affsettingarr = unserialize($affsetting['value']);
		//查询用户
		$memberInfo = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		//升级为基本分销等级
		$rlevel = array(0,0,0);
		$total = $this->orderdb -> where(array('member_id' => $this->member_id, 'status' => 2)) -> sum('total');
		$mylevel = 0;
		if($affsettingarr['levelmoney'] <= $total){
		    //更新用户等级
			$mylevel = 1;
	    }
		
		$data['level'] = $mylevel;
		
		//dump($data);
		//if($memberInfo['level'] < $data['level']){
			$ret = $this->memberdb -> where(array('id' => $memberInfo['id'])) -> data($data) -> save();//dump($ret);
			if($ret != 0 && $memberInfo['level'] < $data['level']){
				sendWXMsg($memberInfo['openid'], str_replace('@levelname@', $this->getLevelName(), $affsettingarr['changelevel']));
			}
			//echo $this->memberdb -> getLastSql();
			$mtmdb = M('Member_member');
			$mtmdb -> where(array('smember_id' => $memberInfo['id'])) -> data($data) -> save();
		//}
	}
	
	//获取等级名称
	public function getLevelName(){
		$memberInfo = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		$namelist = $this -> affsettingarr['levelname'];
		$namelist[] = $this -> affsettingarr['levelnamebase'];
		$namelist[] = '普通会员';
		$namelist = array_reverse($namelist);
		return $namelist[$memberInfo['level']];
	}
	
	
	
	//获取父子级会员数组8级
	public function getUserArr($pid=0,$arr=array(), $deep = 0){
		$re=$this->memberdb->where(array('id'=>$pid,'site_id'=>$this->site_id))->find();
		//8级返回
		if($deep == 8){return $arr;}
		if(!is_array($re)){
			return $arr;
		}else{
			$re['deep'] = $deep + 1;
			//if($re['level'] > 0){
			    $arr[]=$re;
			//}
			$deep ++;
			return $this->getUserArr($re['pid'],$arr, $deep);
		}
	}
	
	//获取父子级会员数组无限级
	public function getUserArrAll($pid=0,$arr=array(), $deep = 0){
		$re=$this->memberdb->where(array('id'=>$pid,'site_id'=>$this->site_id))->find();
		if(!is_array($re)){
			return $arr;
		}else{
			if($re['level'] > 1){
			    $arr[]=$re;
			}
			$deep ++;
			return $this->getUserArrAll($re['pid'],$arr, $deep);
		}
	}
	
	
	
	
	//获取VIP分成用户列表(需要分成的用户列表)
	public function getuserlist(){
		$ordermember = $this->memberdb -> where(array('id' => $this->order['member_id'])) -> find();
		
		$affsettingarr = $this -> affsettingarr;
		
		$list = $this -> getUserArr($ordermember['pid']);
		foreach($list as $k => $v){
			if($v['level'] > 0){
			    $list[$k]['aff'] = $affsettingarr['level'][$k];
			}else{
				$list[$k]['aff'] = 0;
			}
		}
		return $list;
	}
	
	//获取总代分成总额
	public function getuserlistAll(){
		$ret = array();
		$ordermember = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		$list = $this -> getUserArrAll($ordermember['pid']);
		$affList = array_reverse($this->affsettingarr['rlevel']);//dump($affList);
		foreach($list as $k => $v){
			
			if($k == 0){
				$aff = $affList[$v['level']-2];
			}else{
				$aff = $affList[$v['level']-2] - $list[$k - 1]['aff'];
			}
			if($aff > 0){
			    $list[$k]['aff'] = $aff;
				
				$ret[] = $list[$k];
			}
			//$list[$k]['aff'] = $affList[$v['level']-2];
		}
		return $ret;
	}
	
	//写入分成日志
	
	public function insertlogAll(){
		$db = M('Member_account_log');
		$productList = $this->getmoney();
		$userList = $this->getuserlistAll();
		
		foreach($userList as $k => $v){
			$money = 0;
			foreach($productList as $key => $val){
				$data['member_id'] = $v['id'];
				$data['user_id'] = 0;
				$data['pdstate'] = 3; //类型3为分成
				$data['dateline'] = time();
				$data['changenum'] = round($val['aff_money']*$v['aff']/100,2);
				$data['order_id'] = $this->order['id'];
				$data['order_sn'] = $this->order['ordernumber'];
				$data['product_id'] = $val['product_id'];
				$data['num'] = $val['num'];
				$data['site_id'] = $this->site_id;
				$data['attr'] = $val['attr'];
				$data['remark'] = '粉丝下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$data['changenum'];
				$data['goodsMoney'] = $val['total'];
				if($data['changenum'] > 0){
					$money += $data['changenum'];
					$db -> data($data) -> add();
				}
			}
			if($money > 0){
				//信息通知
				$msg = '粉丝下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$money;
				sendWXMsg($v['openid'], $msg);
			}
		}
	}
	
	
	public function insertlog(){
		$db = M('Member_account_log');
		$productList = $this->getmoney();
		$userList = $this->getuserlist();
		foreach($userList as $k => $v){
			$money = 0;
			foreach($productList as $key => $val){
				$data['member_id'] = $v['id'];
				$data['user_id'] = 0;
				$data['pdstate'] = 3; //类型3为分成
				$data['dateline'] = time();
				$data['changenum'] = round($val['aff_money']*$v['aff']/100,2);
				$data['order_id'] = $this->order['id'];
				$data['order_sn'] = $this->order['ordernumber'];
				$data['product_id'] = $val['product_id'];
				$data['num'] = $val['num'];
				$data['site_id'] = $this->site_id;
				$data['attr'] = $val['attr'];
				$data['remark'] = '粉丝下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$data['changenum'];
				$data['goodsMoney'] = $val['total'];
				if($data['changenum'] > 0){
					$money += $data['changenum'];
					$db -> data($data) -> add();
				}
			}
			if($money > 0){
				//信息通知
				$msg = '粉丝下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$money;
				sendWXMsg($v['openid'], $msg);
			}
		}
		//总代分成写入
		//$this->insertlogAll();
	}
	
	//撤消一个分成
	public function loggoback(){
		
	}
	
	//获取分成总额
	public function getmoney(){
		return $this -> saledb -> where(array('order_id' => $this->order['id'])) -> Field('(aff_money*num) as aff_money,product_id,total,num,attr') -> select();
	}
	
	//返回错误信息
	public function getError(){
		return $this->error['info'];
	}
}